package com.monkey.web.platform.service.impl;

import com.monkey.core.domain.organization.Organization;
import com.monkey.core.domain.user.User;
import com.monkey.core.domain.user.UserRepository;
import com.monkey.core.plugin.dto.MonkeyDto;
import com.monkey.core.plugin.service.BaseTreeableServiceImpl;
import com.monkey.core.repository.search.SearchOperator;
import com.monkey.core.repository.search.Searchable;
import com.monkey.web.platform.service.OrganizationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * Project  : monkey
 * Author   : Wu Tian Qiang
 * Date     : 2016/10/14 18:39:22
 */
@Service
public class OrganizationServiceImpl extends BaseTreeableServiceImpl<Organization, Long> implements OrganizationService {

    @Autowired
    private UserRepository userRepository;

    @Override
    public void addOrganization(MonkeyDto monkeyDto) {
        Long parentId = monkeyDto.getLong("parentId");
        Organization parent = findOne(parentId);
        Organization instance = Organization.createFromMonkeyDto(monkeyDto);
        appendChild(parent, instance);
    }

    @Override
    public void modifyOrganization(MonkeyDto monkeyDto) {
        Long parentId = monkeyDto.getLong("parentId");
        Organization parent = findOne(parentId);
        Organization instance = findOne(monkeyDto.getLong("id"));
        Organization.modifyFromMonkeyDto(instance, monkeyDto);
        updateSelfAndChild(instance, parentId, parent.makeSelfAsNewParentIds(), monkeyDto.getInteger("weight"));

    }

    @Override
    public void removeOrganizations(Long[] ids) {
        for (Long id : ids) {
            Organization tree = findOne(id);
            deleteSelfAndChild(tree);
        }
    }

    public Page<User> findUsersByOrganization(Organization organization, Searchable searchable) {
        List<Long> ids = findChildrenIds(organization);
        ids.add(organization.getId());

        searchable.addSearchFilter("organization", SearchOperator.in, ids);
        return userRepository.findAll(searchable);
    }

}
